﻿using System;
using System.Linq.Expressions;

namespace Gmantis.Controls.DataGrid
{
    public static class DataGridFilterHelper
    {
        public static Predicate<object> BuildFilterPredicate<T>(DataGridColumnValue<DataGridFilterState>[] filterStates, DataGridFilterCombination concat)
        {
            Predicate<object> predicate = null;
            Expression left = null;
            if (filterStates != null)
            {
                ParameterExpression expression2 = Expression.Parameter(typeof(T), "i");
                foreach (DataGridColumnValue<DataGridFilterState> value2 in filterStates)
                {
                    FilterDescription filterDescription = new FilterDescription(value2.Column.ActualFilterMemberPath, value2.Value);
                    Expression right = filterDescription.BuildExpressionBody<T>(filterDescription, expression2);
                    if (concat == DataGridFilterCombination.And)
                    {
                        left = (left == null) ? right : Expression.AndAlso(left, right);
                    }
                    else
                    {
                        left = (left == null) ? right : Expression.OrElse(left, right);
                    }
                }
                left = (left == null) ? Expression.Constant(true) : left;
                if (filterStates.Length > 0)
                {
                    Func<T, bool> lambda = Expression.Lambda<Func<T, bool>>(left, new ParameterExpression[] { expression2 }).Compile();
                    predicate = delegate(object o)
                    {
                        if (o == null)
                        {
                            return false;
                        }
                        return lambda((T)o);
                    };
                }
            }
            return predicate;
        }

        public static T GetPropertyValue<T>(object source, string propertyPath)
        {
            return source.GetPropertyValue<T>(propertyPath);
        }
    }
}
